import { PongGame } from './pong-game.js';
import { AudioManager } from './audio-manager.js';
import { ParticleSystem } from './particle-system.js';

/**
 * 游戏主控制器
 * @description 管理游戏的整体流程和用户交互
 */
class GameController {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');

        // 初始化游戏组件
        this.game = new PongGame(this.canvas, this.ctx);
        this.audioManager = new AudioManager();
        this.particleSystem = new ParticleSystem();

        // 游戏状态
        this.isRunning = false;
        this.isPaused = false;
        this.gameTime = 0;
        this.startTime = 0;

        // DOM元素
        this.overlay = document.getElementById('game-overlay');
        this.overlayTitle = document.getElementById('overlay-title');
        this.overlayMessage = document.getElementById('overlay-message');

        // 绑定事件
        this.bindEvents();

        // 初始化游戏
        this.init();
    }

    /**
     * 初始化游戏
     */
    init() {
        this.showWelcomeScreen();
        this.updateUI();
        this.gameLoop();
    }

    /**
     * 绑定事件监听
     */
    bindEvents() {
        // 按钮事件
        document.getElementById('start-btn').addEventListener('click', () => {
            this.startGame();
        });

        document.getElementById('pause-btn').addEventListener('click', () => {
            this.togglePause();
        });

        document.getElementById('reset-btn').addEventListener('click', () => {
            this.resetGame();
        });

        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.handleKeyDown(e);
        });

        document.addEventListener('keyup', (e) => {
            this.handleKeyUp(e);
        });

        // 窗口事件
        window.addEventListener('resize', () => {
            this.handleResize();
        });
    }

    /**
     * 开始游戏
     */
    startGame() {
        this.isRunning = true;
        this.isPaused = false;
        this.startTime = Date.now();
        this.gameTime = 0;

        this.game.start();
        this.audioManager.playSound('start');
        this.hideOverlay();

        // 更新按钮状态
        document.getElementById('start-btn').textContent = '重新开始';
        document.getElementById('pause-btn').disabled = false;
    }

    /**
     * 暂停/恢复游戏
     */
    togglePause() {
        if (!this.isRunning) return;

        this.isPaused = !this.isPaused;
        this.game.setPaused(this.isPaused);

        if (this.isPaused) {
            this.showPauseScreen();
            this.audioManager.playSound('pause');
        } else {
            this.hideOverlay();
            this.audioManager.playSound('resume');
        }

        document.getElementById('pause-btn').textContent = this.isPaused ? '恢复' : '暂停';
    }

    /**
     * 重置游戏
     */
    resetGame() {
        this.isRunning = false;
        this.isPaused = false;
        this.gameTime = 0;
        this.startTime = 0;

        this.game.reset();
        this.particleSystem.clear();
        this.audioManager.playSound('reset');

        this.showWelcomeScreen();
        this.updateUI();

        // 重置按钮状态
        document.getElementById('start-btn').textContent = '开始游戏';
        document.getElementById('pause-btn').textContent = '暂停';
        document.getElementById('pause-btn').disabled = true;
    }

    /**
     * 显示欢迎界面
     */
    showWelcomeScreen() {
        this.overlayTitle.textContent = '欢迎来到弹球大战！';
        this.overlayMessage.textContent = '点击"开始游戏"开始对战';
        this.showOverlay();
    }

    /**
     * 显示暂停界面
     */
    showPauseScreen() {
        this.overlayTitle.textContent = '游戏暂停';
        this.overlayMessage.textContent = '点击"恢复"继续游戏';
        this.showOverlay();
    }

    /**
     * 显示游戏结束界面
     */
    showGameOverScreen(winner) {
        this.overlayTitle.textContent = `游戏结束！`;
        this.overlayMessage.textContent = `获胜者: ${winner}`;
        this.showOverlay();

        this.audioManager.playSound('gameOver');
    }

    /**
     * 显示覆盖层
     */
    showOverlay() {
        this.overlay.classList.remove('hidden');
    }

    /**
     * 隐藏覆盖层
     */
    hideOverlay() {
        this.overlay.classList.add('hidden');
    }

    /**
     * 处理键盘按下事件
     */
    handleKeyDown(e) {
        if (!this.isRunning || this.isPaused) return;

        switch (e.code) {
            case 'KeyW':
                this.game.movePlayer1('up');
                break;
            case 'KeyS':
                this.game.movePlayer1('down');
                break;
            case 'ArrowUp':
                this.game.movePlayer2('up');
                break;
            case 'ArrowDown':
                this.game.movePlayer2('down');
                break;
            case 'Space':
                e.preventDefault();
                this.togglePause();
                break;
        }
    }

    /**
     * 处理键盘释放事件
     */
    handleKeyUp(e) {
        if (!this.isRunning || this.isPaused) return;

        switch (e.code) {
            case 'KeyW':
            case 'KeyS':
                this.game.stopPlayer1();
                break;
            case 'ArrowUp':
            case 'ArrowDown':
                this.game.stopPlayer2();
                break;
        }
    }

    /**
     * 处理窗口大小变化
     */
    handleResize() {
        // 可以在这里添加响应式处理逻辑
        this.game.handleResize();
    }

    /**
     * 更新UI显示
     */
    updateUI() {
        // 更新分数
        document.getElementById('player1-score').textContent = this.game.player1Score;
        document.getElementById('player2-score').textContent = this.game.player2Score;

        // 更新球速
        document.getElementById('ball-speed').textContent = Math.round(this.game.ballSpeed);

        // 更新回合数
        document.getElementById('round-count').textContent = this.game.roundCount;

        // 更新游戏时间
        if (this.isRunning && !this.isPaused) {
            this.gameTime = Math.floor((Date.now() - this.startTime) / 1000);
        }

        const minutes = Math.floor(this.gameTime / 60);
        const seconds = this.gameTime % 60;
        document.getElementById('game-time').textContent =
            `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    /**
     * 游戏主循环
     */
    gameLoop() {
        if (this.isRunning && !this.isPaused) {
            this.game.update();
            this.particleSystem.update();

            // 检查游戏结束条件
            if (this.game.checkGameOver()) {
                const winner = this.game.getWinner();
                this.showGameOverScreen(winner);
                this.isRunning = false;
            }
        }

        // 渲染
        this.render();

        // 更新UI
        this.updateUI();

        // 继续循环
        requestAnimationFrame(() => this.gameLoop());
    }

    /**
     * 渲染游戏画面
     */
    render() {
        // 清空画布
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 渲染游戏对象
        this.game.render(this.ctx);

        // 渲染粒子效果
        this.particleSystem.render(this.ctx);

        // 渲染UI元素
        this.renderUI();
    }

    /**
     * 渲染UI元素
     */
    renderUI() {
        // 渲染游戏状态指示器
        if (this.isRunning) {
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
            this.ctx.fillRect(10, 10, 100, 30);
            this.ctx.fillStyle = '#fff';
            this.ctx.font = '16px Arial';
            this.ctx.fillText(this.isPaused ? '暂停' : '游戏中', 20, 30);
        }
    }
}

// 当DOM加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    new GameController();
}); 